const express = require('express');
const path = require('path');
const app = express();
const { SuperRequest } = require('./tools');

// Dev
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); // This origin is UI dev server
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

// Configure static folder
app.use(express.static(path.join(__dirname, '../build')));

// Work as Proxy
app.get(/test/, async (req, res, next) => {
    const method = req.method;
    const targetUrl = req.path.replace('/test', '');
    const body = req.body;
    const response = await SuperRequest(method, targetUrl, body);
    res.send(response.data);
});

// Send resource
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../build', 'index.html'));
});

// App start
const port = process.env.PORT || 3005;
app.listen(port, () => {
    console.log(`app listening on port: ${port}`);
});